package com.atguigu.gulimall.product.controller;

import java.util.Arrays;
import java.util.Map;

import com.atguigu.common.valid.AddGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.atguigu.gulimall.product.entity.BrandEntity;
import com.atguigu.gulimall.product.service.BrandService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;


/**
 * 品牌
 *
 * @author chenhaifu
 * @email 542704865@qq.com
 * @date 2021-03-04 21:22:43
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     * BindingResult接受的话就会抛到common的处理异常类里去
     */
    @RequestMapping("/save")
    public R save(@RequestBody @Validated(AddGroup.class) BrandEntity brand/**,BindingResult bindingResult**/) {
//        if (bindingResult.hasErrors()) {
//            //组装 字段:错误信息
//            Map<String, String> map = new LinkedHashMap<String, String>();
//            //获取遍历错误字段
//            bindingResult.getFieldErrors().forEach(item -> {
//                String message = item.getDefaultMessage();
//                String field = item.getField();
//                map.put(field,message);
//            });
//            return R.error(400,"品牌添加字段校验错误").put("data",map);
//        } else {
        brandService.save(brand);

        return R.ok();
//        }
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody BrandEntity brand) {
        brandService.updateDetailById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds) {
        brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
